package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * lcd  2020/6/5
 * Description:
 */
@EnableConfigurationProperties(UploadProperties.class)
@Service
@Slf4j
public class UploadService {
//    private static final List<String> ALLOW_TYPES = Arrays.asList("image/jpeg", "image/gif", "image/png", "image/jpg");
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private UploadProperties uploadProperties;

    public String uploadImage(MultipartFile file) {

        try {
            //文件后缀校验
            String contentType = file.getContentType();
            if(!uploadProperties.getAllowTypes().contains(contentType)){
                log.error("文件类型不合法,{}",file.getOriginalFilename());
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //文件类型检验
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                log.error("文件内容不合法,{}",file.getOriginalFilename());
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //上传到本地
//            File dest=new File("C:/javaCode/demo-project/leyou/upload",file.getOriginalFilename());
            //保存文件
//            file.transferTo(dest);
            //上传到fastdfs
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            //返回路径
            return uploadProperties.getBaseUrl()+storePath.getFullPath();

        } catch (IOException e) {
            log.error("[文件上传]上传文件失败,{}",file.getOriginalFilename(),e);
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }


    }
}
